// src/store/modules/menuTab.js
import * as c from '@/util/config'
import * as u from '@/util/util'

export default {
  namespaced: true,
  state: () => ({
    openMenu: u.getSession(c.sessionKey.OPEN_MENU) ?? [c.HOME_PAGE],
    thisMenu: u.getSession(c.sessionKey.THIS_MENU_KEY) ?? c.HOME_PAGE.id,
  }),
  mutations: {
    setOpenMenu(state, menuList) {
      state.openMenu = menuList
      u.setSession(c.sessionKey.OPEN_MENU, menuList)
    },
    addOpenMenu(state, menu) {
      if (!state.openMenu.some(m => m.id === menu.id)) {
        state.openMenu.push(menu)
        u.setSession(c.sessionKey.OPEN_MENU, state.openMenu)
      }
    },
    delOpenMenu(state, id) {
      const index = state.openMenu.findIndex(x => x.id === id)
      if (index !== -1) {
        state.openMenu.splice(index, 1)
        u.setSession(c.sessionKey.OPEN_MENU, state.openMenu)
      }
    },
    setThisMenu(state, id) {
      state.thisMenu = id
      u.setSession(c.sessionKey.THIS_MENU_KEY, id)
    },
  },
  actions: {
    closeAll({ commit, state }) {
      commit('setOpenMenu', [state.openMenu[0]])
      commit('setThisMenu', state.openMenu[0].id)
    },
    closeLeft({ state, commit }) {
      const index = state.openMenu.findIndex(x => x.id === state.thisMenu)
      if (index > 1) {
        const newMenu = [state.openMenu[0], ...state.openMenu.slice(index)]
        commit('setOpenMenu', newMenu)
      }
    },
    closeRight({ state, commit }) {
      const index = state.openMenu.findIndex(x => x.id === state.thisMenu)
      if (index !== -1 && index < state.openMenu.length - 1) {
        const newMenu = state.openMenu.slice(0, index + 1)
        commit('setOpenMenu', newMenu)
      }
    },
    closeOther({ state, commit }) {
      const index = state.openMenu.findIndex(x => x.id === state.thisMenu)
      if (index !== -1) {
        const newMenu = [state.openMenu[0], state.openMenu[index]].filter((v, i, a) => a.findIndex(t => t.id === v.id) === i)
        commit('setOpenMenu', newMenu)
      }
    },
  },
}
